<?php


namespace app\app\controller;


use form\Form;
use think\Db;

class Business extends WxUser
{
    protected $businessInfo;
    protected $businessId;
    protected $employInfo;
    protected $employId;

//    protected $role;

    protected function initialize()
    {
        parent::initialize();
        //登录查看用户身份 做出判断 商家返回商家信息
        // 员工返回员工信息 返回商家信息 1商家 2用户
        //      $this->role = $_SERVER['HTTP_ROLE'] ?? '';
        if (empty($this->role)) {
            responseJson(-100, '请输入登录身份');
        }
        if ($this->role == 1) {
            //获取商家登录信息
            $business = Db::name('business')
                ->where(['member_id' => $this->memberId, 'is_del' => 0])
                ->find();
        } else if ($this->role == 2) {
            $employ = Db::name('employ')
                ->where(['member_id' => $this->memberId, 'is_del' => 0])
                ->find();
            if (!$employ) {
                responseJson(-100, '员工信息不存在');
            }
            if ($employ['status'] != 1) {
                responseJson(-200, '员工状态异常，请联系管理员');
            }
            //获取商家信息
            $business = Db::name('business')
                ->where(['id' => $employ['business_id'], 'is_del' => 0])
                ->find();
            $this->employInfo = $employ;
            $this->employId = $employ['id'];
        } else {
            responseJson(-200, '请输入正常角色代码');
        }
        if (!$business) {
            responseJson(-100, '商家信息不存在');
        }
        if ($business['status'] != 1) {
            responseJson(-200, '商家状态异常，请联系管理员');
        }
        if (!strpos($business['food_business_license'], 'ttp')) {
            $business['food_business_license'] = config('wechat.url') . $business['food_business_license'];
        }
        if (!strpos($business['business_license'], 'ttp')) {
            $business['business_license'] = config('wechat.url') . $business['business_license'];
        }
        $operate_type = Db::name('operate_type')->find($business['operate_type']);
        $business['operate_type_name'] = $operate_type['name'];
        $operate_cate_id = explode(',', $business['operate_cate']);
        $operate_cate = Db::name('operate_cate')->where('id', 'in', $operate_cate_id)->column('name');
        $operate_cate = implode('/', $operate_cate);
        $business['operate_cate_name'] = $operate_cate;

        $this->businessInfo = $business;
        $this->businessId = $business['id'];
    }

    /**
     * 获取商家信息
     */
    public function getBusinessInfo()
    {
        //商家二维码重新生成
        if (!$this->businessInfo['code_url']) {
            $code_url = qrcode('business_id', $this->businessId, 'pages1/staffMessage/staffMessage');
            Db::name('business')->update([
                'id' => $this->businessId,
                'code_url' => $code_url
            ]);
            $this->businessInfo['code_url'] = $code_url;
        }
        $order_dnum = Db::name('order')->where([
            ['business_id', '=', $this->businessId],
            ['status', '=', 2],
            ['is_del', '=', 0],
        ])->count();
        $this->businessInfo['order_dnum'] = $order_dnum;
        $this->businessInfo['sales_volume'] = $this->salesVolume();
        //todo 减碳
//        $this->businessInfo['reduction'] = 652;
        msg(0, '申请已通过', $this->businessInfo);
    }

    //商家数据统计
    public function getBusinessDataCount()
    {
        //销售总额 订单总额 提现金额
        $order_num = Db::name('order')->where([
            ['business_id', '=', $this->businessId],
            ['status', 'in', [3, 6]],
            ['is_del', '=', 0],
        ])->count();
        $tixian_volume = Db::name('business_finance')->where([
            'business_id' => $this->businessId,
            'status' => 1,
            'type' => 2
        ])->sum('true_money');
        $data['sales_volume'] = $this->salesVolume();
        $data['order_num'] = $order_num;
        $data['tixian_volume'] = $tixian_volume;
        msg(0, '查询成功', $data);
    }

    //获取销售总额
    public function salesVolume()
    {
        $sales_volume = Db::name('order')->where([
            ['business_id', '=', $this->businessId],
            ['status', 'in', [3, 6]],
            ['is_del', '=', 0],
        ])->sum('price');
        return $sales_volume;
    }

    //商家近七天销售统计
    public function saleCountList()
    {
        $order_where[] = ['status', 'in', [2, 3, 6]];
        $order_where[] = ['is_del', '=', 0];
        for ($i = 7; $i >= 1; $i--) {
            $daysAgo[] = date('m.d', strtotime(-$i . " days"));
            $timescope = getTimestamp(-$i);
            $where[] = ['pay_time', 'between', [$timescope[0], $timescope[1]]];
            $price[] = Db::name('order')
                ->where($where)
                ->where($order_where)
                ->sum('pay_money');
        }
        $data['date'] = $daysAgo;
        $data['num'] = $price;
        msg(0, '', $data);
    }

    //获取员工信息
    public function getEmployInfo()
    {
        msg(0, '查询成功', $this->employInfo);
    }

    /**
     * 获取商家经营分类
     */
    public function getBusinessCate()
    {
        //       $cate_ids = explode(',', $this->businessInfo['operate_cate']);
        $data_list = Db::name('operate_cate')
//            ->where('id', 'in', $cate_ids)
            ->where('is_del', '=', 0)
            ->select();
        msg(0, '查询完成', $data_list);
    }

    /**
     * 获取列表商家食品袋列表
     */
    public function getGoodsList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['is_del', '=', 0];
        $where[] = ['business_id', '=', $this->businessId];
        if ($data['status']) {
            $where[] = ['status', '=', $data['status']];
        }
        $data_list = Db::name('goods')
            ->where($where)
            ->paginate($length, false, [
                'page' => $page
            ])
            ->each(function ($item) {
                $item['is_able']=1;
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }

    /**
     *  创建惊喜袋
     */
    public function createFoodBag()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $create_time = time();
            $labels = implode('/', $data['labels']);
            $cate_ids = implode(',', $data['cate_ids']);
            $result = $this->validate($data, 'Goods.insert');
            if (true !== $result) {
                msg(-1, $result, '');
            }
            $qu_time = explode('-', $data['qu_time']);
            $purchase_time = explode('-', $data['purchase_time']);
            $insert_data = array(
                'name' => $data['name'],//名称
                'business_id' => $this->businessId,
                'img' => $data['img'],//图片url
                'cate_id' => $cate_ids, //分类 单一
                'labels' => $labels,    // 数组形式 饮料/面包/随机
                'price' => $data['price'],  //销售价格
                'old_price' => $data['old_price'],  //原价
                'inventory' => $data['inventory'],  //库存 第二天的不设置 直接自动下架
                'is_ming' => $data['is_ming'],  //是否明日预售
                //'inventory_ming' => $data['inventory_ming'] ? $data['inventory_ming'] : 0,   //明日库存
                'qu_time_start' => $qu_time[0], // '取货时间开始',
                'qu_time_end' => $qu_time[1],     //取货结束时间
                'purchase_time_start' => $purchase_time[0],  //可购买时间1
                'purchase_time_end' => $purchase_time[1],  //可购买时间2
                'weight' => $data['weight'],
                'status' => 2,
                'what' => $data['detail'],//'解释'
                'set_time' => $create_time,//设置时间
                'create_time' => $create_time //创建时间
            );
            $goodsLab = Db::name('goods_lab')->where(['name' => $data['labels'][0]])->find();
            if (!$goodsLab) {
                msg(-1, '标签不存在', 0);
            }
            $co2 = $goodsLab['ef'] * ($data['weight'] / 1000);
            $insert_data['co2'] = $co2;
            if (mb_strlen($insert_data['what']) > 100) {
                msg(-1, '食品袋描述过长', 0);
            }
            if ($insert_data['is_ming'] == 1) {
                $qu_time_ming = explode('-', $data['qu_time_ming']);
                $purchase_time_ming = explode('-', $data['purchase_time_ming']);
                $insert_data['qu_time_start_ming'] = $qu_time_ming[0];
                $insert_data['qu_time_end_ming'] = $qu_time_ming[1];
                $insert_data['purchase_time_start_ming'] = $purchase_time_ming[0];
                $insert_data['purchase_time_end_ming'] = $purchase_time_ming[1];
                $insert_data['inventory_ming'] = $data['inventory_ming'] ? $data['inventory_ming'] : 0;
            }
            $business_ids = explode(',', $this->businessInfo['operate_cate']);
            $diff = array_diff($data['cate_ids'], $business_ids);
//        if (!empty($diff)) {
//            msg(-1, '商家品类错误', '');
//        }
            if (!strpos($insert_data['img'], 'ttp')) {
                $insert_data['img'] = config('wechat.url') . $insert_data['img'];
            }

            $goods_id = Db::name('goods')->insertGetId($insert_data);

            Db::commit();
            msg(0, '查询成功', $goods_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取食品袋详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getGoodsDetail()
    {
        $data = $this->request->param();
        $goods_detail = Db::name('goods')->find($data['goods_id']);

        $cate_id = explode(',', $goods_detail['cate_id']);

        $goods_detail['cate'] = Db::name('operate_cate')
            ->where('id', 'in', $cate_id)
            ->column('name');
        $goods_detail['cate'] = implode(',', $goods_detail['cate']);
        msg(0, '查询完成', $goods_detail);
    }

    //设置明天预售
    public function setGoodsTomorrow()
    {
        $data = $this->request->param();
        $create_time = time();
        $goods_info = Db::name('goods')->where(
            [
                'id' => $data['id'],
                'business_id' => $this->businessId
            ]
        )->find();
        if (!$goods_info) {
            msg(-1, '食品袋所属不正确', '');
        }
        $result = $this->validate($data, 'Goods.update_tomorrow');
        if (true !== $result) {
            msg(-1, $result, '');
        }
        $qu_time_ming = explode('-', $data['qu_time_ming']);
        $purchase_time_ming = explode('-', $data['purchase_time_ming']);
        $update = array(
            'id' => $data['id'],
            'inventory_ming' => $data['inventory_ming'],
            'qu_time_start_ming' => $qu_time_ming[0], // '明天取货时间开始',
            'qu_time_end_ming' => $qu_time_ming[1],     //明天取货结束时间
            'purchase_time_start_ming' => $purchase_time_ming[0],  //明天可购买时间1
            'purchase_time_end_ming' => $purchase_time_ming[1],  //明天可购买时间2
            'set_time' => $create_time,//设置时间
            'is_ming' => 1
        );
        Db::startTrans();
        try {
            $result = Db::name('goods')->update($update);
            Db::commit();
            msg(0, '查询成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
        //惊喜袋id
        //明日库存数量
        //领取可取时间开始 可取时间结束
    }

    //编辑食品袋
    public function editGoods()
    {
        $data = $this->request->param();
        // 价格 原价 当天库存
        // 可取时间1 可取时间2
        // 可买时间1 可买时间2
        // 是否明日预售 明日库存
        // 明日可取时间1 明日可取时间2
        // 明日可买时间1 明日可买时间2
        $result = $this->validate($data, 'Goods.edit');
        if (true !== $result) {
            msg(-1, $result, '');
        }
        $create_time = time();
        $qu_time = explode('-', $data['qu_time']);
        $purchase_time = explode('-', $data['purchase_time']);

        $update = array(
            'id' => $data['id'],
            'price' => $data['price'],
            'old_price' => $data['old_price'],
            'inventory' => $data['inventory'],

            'qu_time_start' => $qu_time[0],
            'qu_time_end' => $qu_time[1],
            'purchase_time_start' => $purchase_time[0],
            'purchase_time_end' => $purchase_time[1],

            'is_ming' => $data['is_ming'],
            'inventory_ming' => $data['inventory_ming'] ? $data['inventory_ming'] : 0,
            'set_time' => $create_time,//设置时间
        );
        if ($update['is_ming'] == 1) {
            $qu_time_ming = explode('-', $data['qu_time_ming']);
            $purchase_time_ming = explode('-', $data['purchase_time_ming']);
            $update['qu_time_start_ming'] = $qu_time_ming[0];
            $update['qu_time_end_ming'] = $qu_time_ming[1];
            $update['purchase_time_start_ming'] = $purchase_time_ming[0];
            $update['purchase_time_end_ming'] = $purchase_time_ming[1];
            $update['inventory_ming'] = $data['inventory_ming'] ? $data['inventory_ming'] : 0;
        }
        if ($data['detail']){
            $update['what']=$data['detail'];
        }
        // 审核失败重新编辑
        $goods_info = Db::name('goods')->find($data['id']);
        if ($goods_info['status'] == 3) {  //1已上架 2审核中 3未通过 4仓库中
            $update['status'] = 2;
        }
        //重量设置
        if (isset($data['weight']) && $data['weight']) {

            $labels = explode('/', $goods_info['labels']);
            $goodsLab = Db::name('goods_lab')->where(['name' => $labels[0]])->find();
            if (!$goodsLab) {
                msg(-1, '标签不存在', 0);
            }
            $co2 = $goodsLab['ef'] * ($data['weight'] / 1000);
            $update['co2'] = $co2;
            $update['weight']=$data['weight'];
        }
        Db::startTrans();
        try {
            $resultData = Db::name('goods')->update($update);
            Db::commit();
            msg(0, '查询成功', $resultData);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }

    }

    //删除 取消审核
    public function delGoods()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $update = array(
                'id' => $data['id'],
                'is_del' => 1
            );
            $result = Db::name('goods')->update($update);
            Db::commit();
            msg(0, '查询成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //下架 //上架
    public function setGoodsStatus()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $data['id'],
            'status' => $data['status']
        );
        Db::startTrans();
        try {
            $result = Db::name('goods')->update($update);
            Db::commit();
            msg(0, '查询成功', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //账号中心数据
    public function accountData()
    {
        //可提现金额 min_tixian amount 未体现营业额 总营业额 已提现总营业额
        $a=$this->businessInfo['amount']>=$this->businessInfo['min_tixian']?number_format($this->businessInfo['amount']*(100-$this->businessInfo['commission'])/100,2):0;//可提现金额
        $b=$this->businessInfo['amount'];//未体现营业额
        $c=$this->businessInfo['business_volume'];//总营业额
        $d=Db::name('business_finance')->where([    //已提现总额
            'business_id'=>$this->businessId,
            'type'=>2,
            'status'=>1
        ])->sum('true_money');

        $return['a']=$a;
        $return['b']=$b;
        $return['c']=$c;
        $return['d']=$d;
        // $sales_volume = $this->salesVolume();
        $return['f'] = $this->businessInfo['commission'];
        $return['h'] = $this->businessInfo['amount'];

        $return['min_tixian'] = $this->businessInfo['min_tixian'];

//        //实际到账
//        $return['amount'] = $this->businessInfo['amount'] * (100 - $return['rate']) / 100;
//        $return['amount']=number_format($return['amount'],2);
//
//        //总营业额
//        $return['sales_volume'] = $this->businessInfo['business_volume'];
//        //可提现营业额
//        $return['amount2'] = $this->businessInfo['amount'];
//        //最低提现营业额
//        $return['min_tixian'] = $this->businessInfo['min_tixian'];
        msg(0, '查询成功', $return);
    }

    /**
     * 商家提现
     */
    public function BusinessTixian()
    {
        $data = $this->request->param();
        $businessInfo = $this->businessInfo;
        if ($data['amount'] <= 0) {
            msg(-1, '输入正确值', '');
        }
        if ($data['amount'] < $businessInfo['min_tixian']) {
            msg(-1, '最低提现金额' . $businessInfo['min_tixian'], '');
        }
        if ($data['amount'] > $businessInfo['amount']) {
            msg(-1, '提现金额不能大于余额', '');
        }

        Db::startTrans();
        try {
            $insert_data = array(
                'business_id' => $this->businessId,
                'money' => $data['amount'],
                'true_money' => $data['amount'] * ((100 - $this->businessInfo['commission']) / 100),
                'commission' => $this->businessInfo['commission'],
                'type' => 2,
                'tixian_type' => 1, //1银行 2支付宝 3微信

                'tixian_name' => $this->businessInfo['bank_account_name'],//提现开户名
                'tixian_account' => $this->businessInfo['bank_account'], //提现账号
                'tixian_bank' => $this->businessInfo['bank_name'],//提现银行名（银行提现使用）

                'finance_people' => $this->businessInfo['finance_people'], //提现账号
                'finance_phone' => $this->businessInfo['finance_phone'],//提现开户名

                'desc' => '余额提现',
                'status' => 0,//'0未完成 待审核 1已完成 审核完成 提现使用',
                'create_time' => time(),
                'is_count' => 2
            );
            $insert_id = Db::name('business_finance')->insertGetId($insert_data);
            Db::name('business')
                ->where('is_del','=',0)
                ->where('id', '=', $this->businessId)
                ->setDec('amount', $data['amount']);
            Db::commit();
            msg(0, '更新成功', $insert_id);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    /**
     * 获取提现详情
     */
    public  function tixianDetail(){
        $data = $this->request->param();
        $finance=Db::name('business_finance')->find($data['id']);
        $finance['create_time']=date('Y-m-d H:i:s', $finance['create_time']);
        if($finance['is_kuan']==0){
            $finance['status']=0;
        }
        msg(0, '更新成功', $finance);
    }

    //获取提现记录列表
    public function tixianRecordList()
    {
        $data = $this->request->param();
        //'year month'
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $search_time = getMonthTimestampRange($data['year'], $data['month']);
        $where[] = ['business_id', '=', $this->businessId];
        $where[] = ['type', '=', 2];
        $where[] = ['is_count', '=', 2];
        $where[] = ['create_time', 'between', [$search_time[0], $search_time[1]]];

        $data_list = Db::name('business_finance')->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                //$item['status_time']=date('Y-m-d H:i:s',$item['status_time']);
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }


    //获取收入记录列表
    public function tradeRecordList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $search_time = getMonthTimestampRange($data['year'], $data['month']);
        $where[] = ['business_id', '=', $this->businessId];
        $where[] = ['type', '=', 1];
        $where[] = ['is_count', '=', 1];
        $where[] = ['create_time', 'between', [$search_time[0], $search_time[1]]];

        $data_list = Db::name('business_finance')->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                return $item;
            });
        msg(0, '查询完成', $data_list);
    }

    //商家上线  0下线 1上线
    public function BusinessOnline()
    {
        $data = $this->request->param();
        $update = array(
            'id' => $this->businessId,
            'operation_status' => $data['operation_status']
        );
        Db::name('business')->update($update);
        msg(0, '更改成功', $data['operation_status']);
    }


    //获取员工列表
    public function getEmployList()
    {
        $data = $this->request->param();
        $page = input('page/d', 1);
        $length = input('limit/d', 10);
        $where[] = ['e.business_id', '=', $this->businessId];
        $where[] = ['e.is_del', '=', 0];
        $data_list = Db::name('employ')->alias('e')
            ->join('member m', 'e.member_id=m.id')
            ->field('e.*,m.avatarUrl')
            ->where($where)
            ->order('role')
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])
            ->each(function ($item) {
                return $item;
            });
        msg(0, '更改成功', $data_list);
    }

    //设置超级员工 取消超级员工
    public function setManage()
    {
        $data = $this->request->param();
        $employ_info = Db::name('employ')->find($data['employ_id']);
        if ($employ_info['business_id'] != $this->businessId) {
            msg(-1, '员工不属于本商家', '');
        }
        $update = array(
            'id' => $data['employ_id'],
            'role' => $data['role'] //1普通员工 2管理员
        );
        Db::name('employ')->update($update);
        msg(0, '更改成功', $data['operation_status']);
    }

    //删除员工
    public function delEmploy()
    {
        $data = $this->request->param();
        $employ_info = Db::name('employ')->find($data['employ_id']);
        if ($employ_info['business_id'] != $this->businessId) {
            msg(-1, '员工不属于本商家', '');
        }
        $update = array(
            'id' => $data['employ_id'],
            'is_del' => 1
        );
        Db::name('employ')->update($update);
        msg(0, '更改成功', $data['operation_status']);
    }

    //修改商家信息
    public function editBusinessInfo()
    {
        $data = $this->request->param();
        $update_data = array(
            'id' => $this->businessId,
            'name' => $data['name'] ? $data['name'] : $this->businessInfo['name'],
            'phone' => $data['phone'] ? $data['phone'] : $this->businessInfo['phone'],
            'food_business_license' => $data['food_business_license'] ? $data['food_business_license'] : $this->businessInfo['food_business_license'],
            'business_license' => $data['business_license'] ? $data['business_license'] : $this->businessInfo['business_license'],
        );
        Db::name('business')->update($update_data);
        msg(0, '更改成功', '');
        //负责人 name
        //联系电话 phone
        //食品经营许可 food_business_license
        //营业执照 business_license
    }

    //上架魔法袋
    public function goGoods()
    {
        $data = $this->request->param();
        $set_time = time();
        $qu_time = explode('-', $data['qu_time']);
        $purchase_time = explode('-', $data['purchase_time']);
        $update = array(
            'id' => $data['id'],

            'qu_time_start' => $qu_time[0],
            'qu_time_end' => $qu_time[1],
            'purchase_time_start' => $purchase_time[0],
            'purchase_time_end' => $purchase_time[1],
            'status' => 1,
            'inventory' => $data['inventory'],
            'is_ming' => $data['is_ming'],
            'inventory_ming' => $data['inventory_ming'] ? $data['inventory_ming'] : 0,
            'set_time' => $set_time,//设置时间
        );
        if ($update['is_ming'] == 1) {
            $qu_time_ming = explode('-', $data['qu_time_ming']);
            $purchase_time_ming = explode('-', $data['purchase_time_ming']);
            $update['qu_time_start_ming'] = $qu_time_ming[0];
            $update['qu_time_end_ming'] = $qu_time_ming[1];
            $update['purchase_time_start_ming'] = $purchase_time_ming[0];
            $update['purchase_time_end_ming'] = $purchase_time_ming[1];
        }
        Db::startTrans();
        try {
            $resultData = Db::name('goods')->update($update);
            Db::commit();
            msg(0, '查询成功', $resultData);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //商家扫码核销 不设置订单失效问题
    public function verifyOrder()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        if ($this->role == 1) {
            $result = verifyGoodsOrder($order_id, 1, 1, $this->businessId);
        } else {
            $result = verifyGoodsOrder($order_id, 1, 2, $this->employId);
        }
        if ($result == -1) {
            msg(-1, '操作有误', $result);
        }
        msg(0, '更新完成', $result);
    }

    //核销码核销
    public function verifyOrderDigits()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $write_code_digits = $data['write_code_digits'];
        if ($this->role == 1) {
            $result = verifyGoodsOrder($order_id, 2, 1, $this->businessId, $write_code_digits);
        } else {
            $result = verifyGoodsOrder($order_id, 2, 2, $this->employId, $write_code_digits);
        }
        if ($result == -1) {
            msg(-1, '操作有误', $result);
        }
        msg(0, '更新完成', $result);
    }


    //商家订单
    public function getBusinessOrder()
    {
        $data = $this->request->param();
        $where[] = ['is_del', '=', 0];
        $where[] = ['business_id', '=', $this->businessId];
        //用户信息
        //食品信息
        //核销员工信息
        if (isset($data['status']) && $data['status']) {
            if ($data['status'] == 6) {
                $where[] = ['status', 'in', [3, 6]];
            } else {
                $where[] = ['status', '=', $data['status']];
            }
        } else {
            $where[] = ['status', 'in', [2, 3, 4, 5, 6]];
        }
        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        $data_list = Db::name('order')
            ->where($where)
            ->order('create_time desc')
            ->paginate($length, false, [
                'page' => $page
            ])
            ->each(function ($item) {
                $member_info = Db::name('member')
                    ->field('nickname,avatarUrl,mobile')
                    ->find($item['member_id']);
                $goods_info = Db::name('goods')
                    ->field('name,img,qu_time_start,qu_time_end')
                    ->find($item['goods_id']);
                $item['member_info'] = $member_info;
                $item['goods_info'] = $goods_info;
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['qu_time_start'] = date('Y-m-d H:i', $item['qu_time_start']);
                $item['qu_time_end'] = date('Y-m-d H:i', $item['qu_time_end']);
                if ($item['write_time']) {
                    $item['write_time'] = date('Y-m-d H:i:s', $item['write_time']);
                }
                if ($item['pay_time']) {
                    $item['pay_time'] = date('Y-m-d H:i:s', $item['pay_time']);
                }
                if ($item['status'] == 3) {
                    $item['status'] = 6;
                }
                $item['personnel']=[];
                if ($item['write_role']==2){

                    $employ=Db::name('employ')->find($item['write_role_id']);
                    $member=Db::name('member')->find($employ['member_id']);
//                    $memberc=Db::name('member')->find($item['write_role_id']);
//
//                    $personnel=Db::name('employ')->where([
//                        'member_id'=>$item['write_role_id']
//                    ])->find();
//
                    $item['personnel']['name']=$employ['name'];
                    $item['personnel']['avatarUrl']=$member['avatarUrl'];
                }
                return $item;
            });
        msg(0, '更改成功', $data_list);
    }

    //商家订单详情
    public function orderDetail()
    {
        $data = $this->request->param();
        $order_id = $data['order_id'];
        $order_data = Db::name('order')->find($order_id);
        Db::startTrans();
        try {
            if (!$order_data) {
                msg(-1, '订单有误', '');
            }
            if ($order_data['business_id'] != $this->businessId) {
                msg(-500, '订单不属于本商家', '');
            }
            $order_data['create_time'] = date('Y-m-d H:i:s', $order_data['create_time']);
            if ($order_data['write_time']) {
                $order_data['write_time'] = date('Y-m-d H:i:s', $order_data['write_time']);
            }
            if ($order_data['pay_time']) {
                $order_data['pay_time'] = date('Y-m-d H:i', $order_data['pay_time']);
            }
            if ($order_data['tui_time']) {
                $order_data['tui_time'] = date('Y-m-d H:i:s', $order_data['tui_time']);
            }
            if ($order_data['pay_status'] == 1 && (!$order_data['write_code'])) {
                $write_code_digits = rand(1000, 9999);
                $qr_code = qrcode('order_id', $order_id, 'pages1/order/OrderDetails/OrderDetails');
                $update_order = array(
                    'id' => $order_id,
                    'write_code' => $qr_code,
                    'write_code_digits' => $write_code_digits
                );
                Db::name('order')->update($update_order);
                $order_data['write_code'] = $qr_code;
                $order_data['write_code_digits'] = $write_code_digits;
            }
            //获取商品信息
            $goods_info = Db::name('goods')->find($order_data['goods_id']);
            //member_info
            $member_info = Db::name('member')->find($order_data['member_id']);
            $result['order'] = $order_data;
            $result['goods'] = $goods_info;
            $result['member_info'] = $member_info;
            Db::commit();
            msg(0, '', $result);
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    //获取商品评价列表
    public function CommentList()
    {
        $data = $this->request->param();
        $goods_id = $data['goods_id'];
        $fraction = $data['fraction'];
        $comment_date = $data['comment_date'];

        $page = input('page/d', 1);
        $length = input('limit/d', 20);
        //goods_id 商品id
        //年月日 2024-10-10
        //星级
        $where[] = ['business_id', '=', $this->businessId];
        $where[] = ['is_del', '=', 0];
        $where[] = ['status', '=', 1];
        $where[] = ['reply_id', '=', 0];
        if (isset($data['goods_id'])) {
            $where[] = ['goods_id', '=', $data['goods_id']];
        }
        if (isset($data['fraction'])) {
            $where[] = ['score', '=', $data['fraction']];
        }
        if (isset($data['is_date'])) {
            //$where[] = ['create_time', 'between', [strtotime($comment_date),strtotime($comment_date)+86400]];
            if ($data['is_date'] == 1) {
                $c = 'create_time';
            } else {
                $c = 'create_time desc';
            }
        }


        $comment_list = Db::name('comment')->where($where)->order($c)
            ->paginate($length, false, [
                'page' => $page
            ])->each(function ($item) {
                if ($item['anonymous']) {
                    $item['user_name'] = '匿名用户';
                    $item['user_avatar_url'] = config('site.web_default_avatar');
                } else {
                    $member_info = Db::name('member')->find($item['member_id']);
                    $item['user_name'] = $member_info['nickname'];
                    $item['user_avatar_url'] = $member_info['avatarUrl'];
                }
                //评论图片
                $item['img'] = Db::name('comment_img')
                    ->where('comment_id', '=', $item['id'])
                    ->order('sort desc')
                    ->column('img_url');
                $item['create_time'] = date('Y-m-d', $item['create_time']);
                //显示商品
                $goods_info = Db::name('goods')->find($item['goods_id']);
                if ($goods_info) {
                    $item['goods_info'] = $goods_info;
                }
                $item['reply_count'] = Db::name('comment')
                    ->where('reply_id', $item['id'])
                    ->count();
                return $item;
            });
        msg(0, '查询成功', $comment_list);
    }

    //查看评价
    public function commentDetail()
    {
        $data = $this->request->param();
        //获取评论id comment_id
        $comment_info = Db::name('comment')
            ->alias('c')
            ->join('member m', 'c.member_id=m.id')
            ->join('goods g', 'c.goods_id=g.id')
            ->field('c.*,g.name,g.img as goods_img,g.labels as goods_labels,g.price,g.old_price,g.qu_time_start,g.qu_time_end,m.nickname,m.avatarUrl as avatar_url')
            ->where([
                'c.id' => $data['comment_id'],
                'c.status' => 1,
                'c.is_del' => 0
            ])->find();
        if (!$comment_info) {
            msg(-1, '评论不存在', '');
        }
        $comment_info['create_time'] = date('Y-m-d', $comment_info['create_time']);
        if ($comment_info['anonymous'] == 1) {
            $comment_info['nickname'] = '匿名用户';
            $comment_info['avatar_url'] = config('site.web_default_avatar');
        }
        $comment_img = Db::name('comment_img')->where([
            'comment_id' => $data['comment_id']
        ])->order('sort')->column('img_url');
        $comment_info['comment_img'] = $comment_img;
        //回复数据
        $reply_comment = Db::name('comment')->where([
            'is_del' => 0,
            'reply_id' => $data['comment_id']
        ])->order('create_time desc')->select();
        foreach ($reply_comment as $k => $v) {
            $reply_comment[$k]['create_time'] = date('Y-m-d', $v['create_time']);
            if ($v['reply_role'] == 1) {
                $member_info = Db::name('member')->find($v['member_id']);
                $reply_comment[$k]['user_name'] = $member_info['nickname'];
                $reply_comment[$k]['user_avatar_url'] = $member_info['avatarUrl'];
            } else if ($v['reply_role'] == 2) {
                $business_info = Db::name('business')->find($v['business_id']);
                $reply_comment[$k]['user_name'] = $business_info['business_name'];
                $reply_comment[$k]['user_avatar_url'] = $business_info['logo_url'];
            } else if ($v['reply_role'] == 3) {
                $reply_comment[$k]['user_name'] = '资产标注';
                $reply_comment[$k]['user_avatar_url'] = config('site.web_default_avatar');
            }
        }
        $comment_info['reply_comments'] = $reply_comment;
        msg(0, '查询成功', $comment_info);
    }

    //商家回复评论
    public function replyComment()
    {
        $data = $this->request->param();
        Db::startTrans();
        try {
            $comment = Db::name('comment')
                ->where([
                    'id' => $data['comment_id'],
                    'is_del' => 0,
                ])
                ->find();
            if (!$comment) {
                msg(-1, '评论不存在', '');
            }
            $insert_data = array(
                'business_id' => $this->businessId,
                'content' => $data['content'],
                'create_time' => time(),
                'reply_id' => $data['comment_id'],
                'reply_role' => 2
            );
            $comment_id = Db::name('comment')->insertGetId($insert_data);
            //todo 插入消息通知
            sendMessage($comment['member_id'], $this->businessInfo['business_name'] . '回复了你的评价', 4, 3, $this->businessId);
            Db::commit();
            msg(0, '查询成功', '');
        } catch (\Exception $e) {
            Db::rollback();
            msg(-1, $e->getMessage(), '');
        }
    }

    public function getc_cate()
    {
        $id = input('id');
        $query = db('area')->where('pid', $id)->select();
        return json(['code' => 200, 'data' => $query, 'msg' => '获取成功']);
    }


}